package com.example.myapplication01.broadcast;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.myapplication01.R;
import com.example.myapplication01.domain.Student;

public class BroadcastActivity extends AppCompatActivity {

    private MyBroadcastReceiver receiver;
    private MyReceiver myReceiver;
    private LocalBroadcastManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_broadcast);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 注册广播
        receiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter("com.example.myapplication01.broadcast.MyBroadcastReceiver");
        // filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter.setPriority(1);
        registerReceiver(receiver, filter, RECEIVER_EXPORTED);

        myReceiver = new MyReceiver();
        IntentFilter filter2 = new IntentFilter("com.example.myapplication01.broadcast.MyBroadcastReceiver");
        filter2.setPriority(2);
        registerReceiver(myReceiver, filter2, RECEIVER_EXPORTED);

        // 发送广播
        Intent intent = new Intent("com.example.myapplication01.broadcast.MyBroadcastReceiver");
        intent.putExtra("stu", new Student("zhangsan").toString());
        // sendBroadcast(intent); // 无序广播
        // sendOrderedBroadcast(intent, null); // 有序广播

        manager = LocalBroadcastManager.getInstance(BroadcastActivity.this);
        manager.registerReceiver(receiver, filter);
        manager.registerReceiver(myReceiver, filter2);
        manager.sendBroadcast(intent);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // unregisterReceiver(receiver);
        // unregisterReceiver(myReceiver);
        manager.unregisterReceiver(receiver);
        manager.unregisterReceiver(myReceiver);
    }
}